package com.example.djgzhiyong.androidlevelup

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.widget.Scroller

class CustomView : View {

    private var lastX: Int = 0
    private var lastY: Int = 0

    private var scroller: Scroller? = null

    constructor(context: Context?, attributes: AttributeSet, defStyle: Int) : super(context, attributes, defStyle) {
        init()
    }

    constructor(context: Context?) : super(context) {
        init()
    }

    constructor(context: Context?, attributes: AttributeSet) : super(context, attributes) {
        init()
    }

    private fun init() {
        scroller = Scroller(context)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        event?.let {
            val x = it.x.toInt()
            val y = it.y.toInt()
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastX = x
                    lastY = y
                }
                MotionEvent.ACTION_MOVE -> {
                    val offsetX = x - lastX
                    val offsetY = y - lastY
//                    layout(left + offsetX, top + offsetY, right + offsetX, bottom + offsetY)

//                    offsetLeftAndRight(offsetX)
//                    offsetTopAndBottom(offsetY)

//                    val layoutParams = getLayoutParams() as ViewGroup.MarginLayoutParams
//                    layoutParams.leftMargin = left + offsetX
//                    layoutParams.topMargin = top + offsetY
//                    setLayoutParams(layoutParams)

//                    (parent as View).scrollBy(-offsetX, -offsetY)

                }

            }
        }
        return true
    }

    override fun computeScroll() {
        super.computeScroll()
        scroller?.let {
            if (it.computeScrollOffset()) {
                (parent as View).scrollTo(it.currX, it.currY)
                invalidate()
            }
        }
    }

    public fun someScroolTo(destX: Int, destY: Int) {
        scroller?.startScroll(scrollX, 0, destX - scaleX.toInt(), 2000)
        invalidate()
    }

}